package entity

import (
	"github.com/astaxie/beego/orm"
	"github.com/gomodule/redigo/redis"
	"nspel/nspel"
	"strconv"
)

type City struct {
	Id         int64  `orm:"pk;auto;column(id)"`
	CountryId  int64  `orm:"column(country_id)"`
	ProvinceId int64  `orm:"column(province_id)"`
	Name       string `orm:"column(name)"`
}

func init() {
	orm.RegisterModel(new(City))
}

func (*City) TableName() string {
	return "city"
}

func (c *City) SelectAllByName(name string) (*[]City, error) {
	key := "city"
	hashKey := "name[\"" + name + "\"]"
	var city []City
	err := nspel.RedisHgetJson(key, hashKey, &city)
	if err == nil {
		return &city, nil
	}
	if err != redis.ErrNil {
		nspel.Error(err)
	}
	_, err = nspel.GetOrmEngine().QueryTable(c.TableName()).Filter("name", name).All(&city)
	if err != nil || len(city) == 0 {
		return &city, err
	}
	nspel.RedisHsetJson(key, hashKey, &city)
	return &city, nil
}

func (c *City) SelectAllByProvinceIdName(provinceId int64, name string) error {
	c.ProvinceId = provinceId
	c.Name = name
	key := "city"
	hashKey := "provinceId[" + strconv.FormatInt(provinceId, 10) + "].name[\"" + name + "\"]"
	err := nspel.RedisHgetJson(key, hashKey, c)
	if err == nil {
		return nil
	}
	if err != redis.ErrNil {
		nspel.Error(err)
	}
	err = nspel.GetOrmEngine().Read(c, "province_id", "name")
	if err != nil {
		return err
	}
	nspel.RedisHsetJson(key, hashKey, c)
	return nil
}

func (c *City) SelectAllByProvinceId(provinceId int64) (*[]City, error) {
	c.ProvinceId = provinceId
	var cities []City
	key := "city"
	hashKey := "provinceId[" + strconv.FormatInt(provinceId, 10) + "]"
	err := nspel.RedisHgetJson(key, hashKey, &cities)
	if err == nil {
		return &cities, nil
	}
	if err != redis.ErrNil {
		nspel.Error(err)
	}
	_, err = nspel.GetOrmEngine().QueryTable(c.TableName()).Filter("province_id", provinceId).All(&cities)
	if err != nil {
		return &cities, err
	} else if len(cities) == 0 {
		return &cities, orm.ErrNoRows
	}
	nspel.RedisHsetJson(key, hashKey, &cities)
	return &cities, nil
}

func (c *City) SelectAllById(id int64) error {
	key := "city"
	hashKey := "id[" + strconv.FormatInt(id, 10) + "]"
	err := nspel.RedisHgetJson(key, hashKey, c)
	if err == nil {
		return nil
	}
	if err != redis.ErrNil {
		nspel.Error(err)
	}
	c.Id = id
	err = nspel.GetOrmEngine().Read(c)
	if err != nil {
		return err
	}
	nspel.RedisHsetJson(key, hashKey, c)
	return nil
}

func (c *City) SelectAll() (*[]City, error) {
	key := "city"
	hashKey := "all"
	var cities []City
	err := nspel.RedisHgetJson(key, hashKey, &cities)
	if err == nil {
		return &cities, nil
	}
	if err != redis.ErrNil {
		nspel.Error(err)
	}
	_, err = nspel.GetOrmEngine().QueryTable(c.TableName()).All(&cities)
	if err != nil {
		return &cities, err
	} else if len(cities) == 0 {
		return &cities, orm.ErrNoRows
	}
	nspel.RedisHsetJson(key, hashKey, &cities)
	return &cities, nil
}
